package com.tigerlee.stopmusic;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

public class UpdateNotificationReceiver extends BroadcastReceiver {
	private NotificationManager mNotificationManager;

	private static final int ONE_SECOND = 1000;
	private static final int ID_NOTIFICATION = 1234;

	public static final String INTENT_ACTION_UPDATE_NOTFICIATION = "com.tigerlee.stopmusic.intent.update_noti";
	public static final String INTENT_ACTION_CANCEL_TASK = "com.tigerlee.stopmusic.intent.cancel_task";
	public static final String INTENT_ACTION_FINISH_TASK = "com.tigerlee.stopmusic.intent.finish_task";

	private static final String TAG = "UpdateNotificationReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.e(TAG, action);
		mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		if (action != null && action.equals(INTENT_ACTION_UPDATE_NOTFICIATION)) {
			createNotification(context);
		} else if (action != null && action.equals(INTENT_ACTION_FINISH_TASK)) {
			mNotificationManager.cancel(ID_NOTIFICATION);
			cancelAlarmRepeating(context);
		}
	}

	private void createNotification(Context context) {
		MyPreference preference = new MyPreference(context);
		// Clear a notification when alarm is not started
		if (preference.isRunning() != true){
			Log.e(TAG, "service is not running anymore");
			// Cancel notification to not receive updating intent anymore
			cancelAlarmRepeating(context);
			return;
		}

		long startTime = preference.getStartTime();
		long stopTime = preference.getStopTime();

		long passedSeconds = System.currentTimeMillis() - startTime;
		long remainSeconds = stopTime - startTime;
		Log.e(TAG, passedSeconds + " " + remainSeconds);

		if (remainSeconds <= passedSeconds) { // Clear a notification if it passed
			Log.e(TAG, "passed seconds... cancel notification");
			cancelAlarmRepeating(context);
			mNotificationManager.cancel(ID_NOTIFICATION);
			return;
		}

		Alarm alarm = new Alarm();
		alarm.setAlarmTimeByTimeMills(preference.getStopTime());

		Builder builder = new NotificationCompat.Builder(context);
		builder.setContentTitle(context.getText(R.string.app_label))
				.setSmallIcon(R.drawable.notification_drawable)
				.setContentText(getNotificationRemainTime(alarm.getRemainTimeToString(), context));
		
		Intent resultIntent = new Intent(context, StopProgressActivity.class);
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
		// Adds the back stack
		stackBuilder.addParentStack(StopMusicActivity.class);
		// Adds the Intent to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =
		        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
		builder.setContentIntent(resultPendingIntent);

		builder.setOngoing(true);
		builder.setProgress((int) (remainSeconds), 0, false);
		// notify first
		mNotificationManager.notify(ID_NOTIFICATION, builder.build());

		builder.setProgress((int) (remainSeconds / ONE_SECOND),
				(int) (passedSeconds / ONE_SECOND), false);
		// Displays the progress bar for the first time.
		mNotificationManager.notify(ID_NOTIFICATION, builder.build());
	}
	
	private void cancelAlarmRepeating(Context context){
		Intent intent = new Intent(context, UpdateNotificationReceiver.class);
		intent.setAction(INTENT_ACTION_UPDATE_NOTFICIATION);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager manager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		manager.cancel(pendingIntent);
		
		// Initialize values of preference...
		MyPreference preference = new MyPreference(context);
		preference.initPreference();
	}

	public String getNotificationRemainTime(String[] param, Context context) {
		long hours = Long.parseLong(param[0]);
		long minutes = Long.parseLong(param[1]);
		long days = Long.parseLong(param[2]);

		param[2] = (days == 0) ? "" : (days == 1) ? context
				.getString(R.string.day) : context.getString(R.string.days,
				Long.toString(days));

		param[1] = (minutes == 0) ? "" : (minutes == 1) ? context
				.getString(R.string.minute) : context.getString(
				R.string.minutes, Long.toString(minutes));

		param[0] = (hours == 0) ? "" : (hours == 1) ? context
				.getString(R.string.hour) : context.getString(R.string.hours,
				Long.toString(hours));

		boolean dispDays = days > 0;
		boolean dispHour = hours > 0;
		boolean dispMinute = minutes > 0;

		int index = (dispDays ? 1 : 0) | (dispHour ? 2 : 0)
				| (dispMinute ? 4 : 0);

		String[] formats = context.getResources().getStringArray(
				R.array.alarm_set);
		String result = String.format(formats[index], param[2], param[0],
				param[1]);
		return result;
	}
}
